package com.light.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.light.common.enums.ExceptionEnum;
import com.light.common.utils.PageUtils;
import com.light.common.utils.Query;
import com.light.common.utils.R;
import com.light.common.vo.MemberRespVO;
import com.light.gulimall.member.dao.MemberDao;
import com.light.gulimall.member.dao.MemberLevelDao;
import com.light.gulimall.member.dto.LoginDTO;
import com.light.gulimall.member.dto.SocialUser;
import com.light.gulimall.member.entity.MemberEntity;
import com.light.gulimall.member.entity.MemberLevelEntity;
import com.light.gulimall.member.exception.PhoneExeception;
import com.light.gulimall.member.exception.UserNameException;
import com.light.gulimall.member.service.MemberService;
import com.light.gulimall.member.util.HttpUtils;
import com.light.gulimall.member.vo.UserRegisterVo;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private MemberService memberService;
    @Autowired
    private MemberLevelDao memberLevelDao;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 用户注册
     *
     * @param vo 注册信息
     * @return 返回结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R userRegister(UserRegisterVo vo) {

        MemberEntity memberEntity = new MemberEntity();
        //校验用户名和手机号是否重复
        memberService.checkUserNameAndPhone(vo);
        //入表
        MemberLevelEntity memberLevelEntity = memberLevelDao.selectOne(new QueryWrapper<MemberLevelEntity>().eq("default_status", 1));
        memberEntity.setLevelId(memberLevelEntity.getId());
        memberEntity.setUsername(vo.getUserName());
        memberEntity.setMobile(vo.getPhone());
        memberEntity.setNickname(vo.getUserName());

        //密码加密
        String encodePwd = new BCryptPasswordEncoder().encode(vo.getPassword());
        memberEntity.setPassword(encodePwd);


        save(memberEntity);
        return R.ok();
    }

    @Override
    public void checkUserNameAndPhone(UserRegisterVo vo) throws PhoneExeception, UserNameException {
        String userName = vo.getUserName();
        String phone = vo.getPhone();
        List<MemberEntity> usernames = list(new QueryWrapper<MemberEntity>().eq("username", userName));
        if (!CollectionUtils.isEmpty(usernames)) {
            throw new UserNameException();
        }
        List<MemberEntity> phones = list(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (!CollectionUtils.isEmpty(phones)) {
            throw new PhoneExeception();
        }
    }

    /**
     * 登录
     *
     * @param dto 登录信息
     * @return 成功则返回登录实体类
     */
    @Override
    public R login(LoginDTO dto) {
        String loginacct = dto.getLoginacct();
        String password = dto.getPassword();
        MemberEntity memberEntity = getOne(new QueryWrapper<MemberEntity>().eq("username", loginacct).or().eq("mobile", loginacct));
        if (memberEntity == null) {
            return R.error(ExceptionEnum.NOT_EXIST_EXCEPTION.getCode(), ExceptionEnum.NOT_EXIST_EXCEPTION.getValue());
        }
        //比对密码
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        boolean matches = bCryptPasswordEncoder.matches(password, memberEntity.getPassword());
        if (!matches) {
            return R.error(ExceptionEnum.PASSWORD_ERROR_EXCEPTION.getCode(), ExceptionEnum.PASSWORD_ERROR_EXCEPTION.getValue());
        }

        MemberRespVO memberRespVO = new MemberRespVO();
        BeanUtils.copyProperties(memberEntity, memberRespVO);
        return R.ok(Collections.singletonMap("data", memberRespVO));
    }

    /**
     * 社交登录
     *
     * @param dto 第三方登录返回信息类
     * @return 成功则返回登录实体类
     */
    @Override
    public R login(SocialUser dto) {

        try {
            String name = "";
            Map<String, String> map = new HashMap<>();
            map.put("access_token", dto.getAccessToken());
            //获取用户信息
            HttpResponse response = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "get", new HashMap<String, String>(), map);
            if (response.getStatusLine().getStatusCode() == 200) {
                String s = EntityUtils.toString(response.getEntity());
                JSONObject jsonObject = JSON.parseObject(s);
                int id = (int) jsonObject.get("id");
                name = (String) jsonObject.get("name");
                String email = (String) jsonObject.get("email");


                MemberEntity memberEntity = getOne(new QueryWrapper<MemberEntity>().eq("uid", id));
                if (ObjectUtils.isEmpty(memberEntity)) {
                    //注册
                    MemberEntity entity = new MemberEntity();
                    entity.setToken(dto.getAccessToken());
                    entity.setExpires(String.valueOf(dto.getExpiresIn()));
                    entity.setUid(String.valueOf(id));
                    entity.setNickname(name);
                    entity.setEmail(email);

                    save(entity);
                    MemberRespVO memberRespVO = new MemberRespVO();
                    BeanUtils.copyProperties(entity,memberRespVO);

                    return R.ok().put("data",memberRespVO);

                } else {
                    //更新状态
                    MemberEntity member = new MemberEntity();
                    member.setId(memberEntity.getId());
                    member.setToken(dto.getAccessToken());
                    member.setExpires(String.valueOf(dto.getExpiresIn()));
                    updateById(member);

                    memberEntity.setToken(String.valueOf(dto.getExpiresIn()));
                    memberEntity.setExpires(dto.getAccessToken());

                    MemberRespVO memberRespVO = new MemberRespVO();
                    BeanUtils.copyProperties(memberEntity,memberRespVO);

                    return R.ok().put("data",memberRespVO);
                }

            }
        } catch (Exception e) {
            return R.error(ExceptionEnum.SOCIAL_LOGIN_EXCEPTION.getCode(), ExceptionEnum.SOCIAL_LOGIN_EXCEPTION.getValue());
        }
        return null;

    }

}